import { getSnackOrderList, createSnackOrder } from '@/api/order'

const state = {
    orderList: [],
    currentOrder: null
}

const mutations = {
    SET_ORDER_LIST(state, orders) {
        state.orderList = orders
    },
    ADD_ORDER(state, order) {
        state.orderList.unshift(order)
    },
    SET_CURRENT_ORDER(state, order) {
        state.currentOrder = order
    },
    UPDATE_ORDER_STATUS(state, { orderId, status }) {
        const order = state.orderList.find(order => order.id === orderId)
        if (order) {
            order.status = status
        }
    }
}

const actions = {
    // 获取零食订单列表
    async getOrders({ commit }, params = {}) {
        try {
            const res = await getSnackOrderList(params)
            if (res.code === 200) {
                // 处理订单数据，添加额外信息
                const processedOrders = res.data.map(order => ({
                    ...order,
                    totalWeight: order.items.reduce((sum, item) => sum + (item.weight * item.quantity), 0),
                    itemCount: order.items.reduce((sum, item) => sum + item.quantity, 0)
                }))
                commit('SET_ORDER_LIST', processedOrders)
                return processedOrders
            }
        } catch (error) {
            return Promise.reject(error)
        }
    },
    
    // 创建零食订单
    async createOrder({ commit, rootState }, orderData) {
        try {
            // 添加订单相关的计算和验证
            const orderItems = rootState.cart.items.map(item => ({
                snackId: item.id,
                quantity: item.quantity,
                price: item.price,
                weight: item.weight
            }))

            const orderInfo = {
                ...orderData,
                items: orderItems,
                totalAmount: rootState.cart.getters.cartTotal,
                totalWeight: rootState.cart.getters.cartWeight,
                shippingFee: orderData.totalWeight > 2000 ? 0 : 8, // 超过2kg免运费
                status: 'pending',
                createTime: new Date().toISOString()
            }

            const res = await createSnackOrder(orderInfo)
            if (res.code === 200) {
                commit('ADD_ORDER', res.data)
                // 清空购物车
                commit('cart/CLEAR_CART', null, { root: true })
                return res.data
            }
        } catch (error) {
            return Promise.reject(error)
        }
    },

    // 取消订单
    async cancelOrder({ commit }, orderId) {
        try {
            const res = await cancelSnackOrder(orderId)
            if (res.code === 200) {
                commit('UPDATE_ORDER_STATUS', { orderId, status: 'cancelled' })
                return res.data
            }
        } catch (error) {
            return Promise.reject(error)
        }
    },

    // 确认收货
    async confirmReceived({ commit }, orderId) {
        try {
            const res = await confirmSnackOrderReceived(orderId)
            if (res.code === 200) {
                commit('UPDATE_ORDER_STATUS', { orderId, status: 'completed' })
                return res.data
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }
}

const getters = {
    // 按状态获取订单
    ordersByStatus: (state) => (status) => {
        return state.orderList.filter(order => order.status === status)
    },
    
    // 获取订单总数
    totalOrders: (state) => state.orderList.length,
    
    // 获取待支付订单
    pendingPaymentOrders: (state) => {
        return state.orderList.filter(order => order.status === 'pending')
    },
    
    // 获取待发货订单
    pendingShipmentOrders: (state) => {
        return state.orderList.filter(order => order.status === 'paid')
    },
    
    // 计算订单总金额
    totalOrderAmount: (state) => {
        return state.orderList.reduce((sum, order) => sum + order.totalAmount, 0).toFixed(2)
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}